package com.zl.csMall.mine.favorites.controller;

import com.zl.csMall.code.LoginCacheMap;
import com.zl.csMall.code.config.token.TokenTriggerAspect;
import com.zl.csMall.mine.favorites.po.Favorites;
import com.zl.csMall.mine.favorites.service.FavoritesService;
import com.zl.csMall.mine.user.po.User;
import com.zl.csMall.util.Util;
import com.zl.csMall.vo.ReturnModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @description: FavoritesController
 * @author: ChenNing
 * @date 2025-10-21 14:18
 */
@CrossOrigin(origins = "*")
@Api(tags = "收藏")
@RestController
@RequestMapping("csMall/mine/favorites")
public class FavoritesController {

    @Autowired
    private FavoritesService favoritesService;

    private final LoginCacheMap loginCacheMap;

    public FavoritesController(LoginCacheMap loginCacheMap) {
        this.loginCacheMap = loginCacheMap;
    }


    /**
     * @description: 新增收藏商品
     * @author ChenNing
     * @date: 2025-10-21 14:39
     */
    @CrossOrigin("*")
    @ApiOperation(value = "新增收藏商品")
    @TokenTriggerAspect
    @PostMapping
    public ReturnModel addFavorites(@RequestHeader(required = false) String token,
                                    @Validated @RequestBody Favorites favorites){
        User user = loginCacheMap.getUser(token);

        boolean existence = favoritesService.isExistence(user.getId(), favorites.getCommodityId(), false);
        if (existence){
            return new ReturnModel(false, "该商品已收藏！");
        }

        favorites.setId(Util.getUuId());
        favorites.setUserId(user.getId());
        favorites.setCreateDate(new Date());
        boolean result = favoritesService.save(favorites);
        if (result){
            return new ReturnModel();
        }
        return new ReturnModel(false, "商品收藏失败！");
    }

    /**
     * @description: 取消商品收藏
     * @author ChenNing
     * @date: 2025-10-21 14:45
     */
    @CrossOrigin("*")
    @ApiOperation(value = "取消收藏")
    @TokenTriggerAspect
    @DeleteMapping
    public ReturnModel deleteFavorites(@RequestHeader(required = false) String token,
                                       @Validated @RequestBody Favorites favorites){
        User user = loginCacheMap.getUser(token);

        boolean result = favoritesService.isExistence(user.getId(), favorites.getCommodityId(), true);
        if (result){
            return new ReturnModel();
        }
        return new ReturnModel(false, "商品取消收藏失败！");
    }

}
